package com.lyfam.velcro.tableTag;

import java.io.IOException;
import java.io.StringWriter;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.JspFragment;
import javax.servlet.jsp.tagext.SimpleTagSupport;

public class ColumnTag extends SimpleTagSupport
{
	private String columnId;
	private String className;
	private String rawHtml;
	private String displayName;
	private String dataField;
	private String itemRenderer;

	public String getColumnId()
	{
		return columnId;
	}

	public void setColumnId(String columnId)
	{
		this.columnId = columnId;
	}

	public String getClassName()
	{
		return className;
	}

	public void setClassName(String className)
	{
		this.className = className;
	}

	public String getRawHtml()
	{
		return rawHtml;
	}

	public void setRawHtml(String rawHtml)
	{
		this.rawHtml = rawHtml == null ? "" : rawHtml;
	}

	@Override
	public void doTag() throws JspException, IOException
	{
		TableTag table = (TableTag) findAncestorWithClass(this, TableTag.class);
		if (table == null)
		{
			throw new JspException("Column tag must be inside a table tag");
		}

		// creating a column html element
		// The display value will be populated using ignl syntax in the table
		// class itself
		ColumnHtmlElement column = (ColumnHtmlElement) table.getColumnById(getColumnId());

		if (column == null)
		{
			column = new ColumnHtmlElement();
			column.setId(getColumnId());
			column.setClassName(getClassName() == null ? "" : getClassName());
			column.setRawHtml(getRawHtml() == null ? "" : getRawHtml());
			column.setValue(getDisplayName() == null ? getColumnId() : getDisplayName());
			column.setDisplayName(getDisplayName() == null ? getColumnId() : getDisplayName());
			column.setDataField(getDataField());
			column.setItemRenderer(getItemRenderer());
			table.addColumn(column);
		}

		if (getItemRenderer() == null)
		{
			JspFragment body = getJspBody();
			StringWriter writer;
			String bodyContent = null;
			if (body != null)
			{
				writer = new StringWriter();
				body.invoke(writer);
				bodyContent = writer.toString();
			}
			column.setBodyContent(bodyContent);
		}

		table.addColumn(column);
	}

	public String getDisplayName()
	{
		return displayName;
	}

	public void setDisplayName(String displayName)
	{
		this.displayName = displayName;
	}

	public String getDataField()
	{
		return dataField;
	}

	public void setDataField(String dataField)
	{
		this.dataField = dataField;
	}

	public String getItemRenderer()
	{
		return itemRenderer;
	}

	public void setItemRenderer(String itemRenderer)
	{
		this.itemRenderer = itemRenderer;
	}

}
